﻿using BepInEx;
using CasselGames.Input;
using HarmonyLib;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
namespace QueenUAV
{
    [BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
    public class Plugin : BaseUnityPlugin
    {
        private const int QueenUAV_ID = 1145141;

        private static bool isActiveQueenUAV;
        private void Awake()
        {
            // Plugin startup logic
            Harmony.CreateAndPatchAll(typeof(Plugin), null);

            Logger.LogInfo($"Plugin {PluginInfo.PLUGIN_GUID} is loaded!");
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(DB_Mgr),"Awake")]
        public static void DB_Mgr_Awake_Prefix(DB_Mgr __instance)
        {
            if(!__instance.m_Item_DB1.sheets[2].list.Exists(a=>a.Index == QueenUAV_ID))
            {
                __instance.m_Item_DB1.sheets[2].list.Add(new Item_DB1.Param()
                {
                    Index = QueenUAV_ID,
                    Sort = 61,
                    Enable = 5,
                    Category = "Accessory",
                    Type = 2000,
                    Tier = 1,
                    Name = "便携式挖矿无人机",
                    Recipe = "WorkChip(10),CharacterChip(10), IronPlate(10), CopperWire(20),Battery(10)",
                    Ability = "Constructing(200)",
                    EffectValue_A = 10,
                    EffectValue_B = 10,
                    Speed = 2,
                    Node = "EOEOEOEOEOEOEOEOEOEOEOE",
                    Description = "挖矿从此不孤单！（召唤无人机挖掘10x10范围内的方块，按Z或右摇杆召唤无人机或收回无人机）"
                });
            }           
        }

        
        [HarmonyPostfix]
        [HarmonyPatch(typeof(DB_Mgr), "Awake")]
        public static void DB_Mgr_Awake_Postfix(DB_Mgr __instance)
        {
            var item = __instance.List_ItemDB.Find(a=>a.Index ==QueenUAV_ID);
            item.T_Name = "便携式挖矿无人机";
            item.Description = "挖矿从此不孤单！（按Z或右摇杆召唤无人机或收回无人机）";
        }

        //替换图标
        [HarmonyPrefix]
        [HarmonyPatch(typeof(ItemInfo), "LoadSpriteStr")]
        public static bool ItemInfo_LoadSpriteStr_Prefix(ItemInfo __instance,ref string __result)
        {
            if (__instance.Index == QueenUAV_ID)
            {
                __result = string.Format("GameScene/UI/UI_Canvas/Icon/Item/{0}/{1}", __instance.Category, "ConstructDrone");
                return false;
            }
            return true;
        }

        //移除装备
        [HarmonyPostfix]
        [HarmonyPatch(typeof(T_Queen), "ItemEquip")]
        public static void T_Queen_ItemEquip_Postfix(T_Queen __instance, ItemInfo _info, bool IsOnlyAdd)
        {
            if(_info.Index != QueenUAV_ID)
            {
                ActiveQueenUAV(false);
            }
        }

        //操作开关
        [HarmonyPostfix]
        [HarmonyPatch(typeof(T_Queen), "Update")]
        public static void T_Queen_Update_Postfix(T_Queen __instance)
        {
            if (__instance.m_AccessoryInfo.Index == QueenUAV_ID)
            {
                if ((Input.GetKeyUp(KeyCode.Z) || Input.GetKeyDown(KeyCode.JoystickButton9))&& !isActiveQueenUAV)
                {
                    ActiveQueenUAV(true);
                }
                else if ((Input.GetKeyUp(KeyCode.Z) || Input.GetKeyDown(KeyCode.JoystickButton9)) && isActiveQueenUAV)
                {
                    ActiveQueenUAV(false);
                }
            }
        }

        //强制通电
        [HarmonyPrefix]
        [HarmonyPatch(typeof(Building_ElecMasonry), "WireCheck")]
        public static bool Building_ElecMasonry_WireCheck_Prefix(Building_ElecMasonry __instance,ref bool __result)
        {            
            if(__instance.m_ID == QueenUAV_ID && isActiveQueenUAV)
            {
                __result = true;
                return false;
            }
            return true;
        }

        //设置临时建筑格数为0
        [HarmonyPrefix]
        [HarmonyPatch(typeof(Building), "BuildingSet", new Type[] {typeof(BuildInfo),typeof(Vector2),typeof(int) })]
        public static void Building_BuildingSet_Prefix(Building __instance, BuildInfo info)
        {
            if (__instance.m_ID == QueenUAV_ID)
            {
                Debug.Log("打开无人机");
                info.Width = 1;
                info.Height = 1;
            }
        }

        //跳过建筑生效检测
        [HarmonyPrefix]
        [HarmonyPatch(typeof(Building), "ActivateCheck")]
        public static bool Building_ActivateCheck_Prefix(Building __instance)
        {
            if(__instance.m_ID==QueenUAV_ID)
            {
                return false;
            }
            return true;
        }

        //跳过建筑生效检测
        [HarmonyPrefix]
        [HarmonyPatch(typeof(Building), "NGT_EffectSet")]
        public static bool Building_NGT_EffectSet_Prefix(Building __instance)
        {
            if (__instance.m_ID == QueenUAV_ID)
            {
                return false;
            }
            return true;
        }

        //不保存临时数据
        [HarmonyPrefix]
        [HarmonyPatch(typeof(PlayDataMgr),"Save")]
        public static void PlayDataMgr_Save_Prefix()
        {
            Building_MiningCompany tmpUAV_Building = null;
            //不保存临时建筑
            for (int i = GameMgr.Instance._BuildingMgr.List_Building.Count - 1; i >= 0; i--) {
                if (GameMgr.Instance._BuildingMgr.List_Building[i].m_ID == QueenUAV_ID)
                {
                    tmpUAV_Building = (Building_MiningCompany)GameMgr.Instance._BuildingMgr.List_Building[i];
                    GameMgr.Instance._BuildingMgr.List_Building.RemoveAt(i);
                    break;
                }
            }
            //不保存临时无人机
            if (tmpUAV_Building != null)
            {
                var drones = (List<MiningDrone>)Traverse.Create(tmpUAV_Building).Field("List_Drone").GetValue();
                for (int i = GameMgr.Instance._T_UnitMgr.List_MDrone.Count - 1; i >= 0; i--)
                {
                    var drone = GameMgr.Instance._T_UnitMgr.List_MDrone[i];
                    if (drones.Contains(drone))
                    {
                        GameMgr.Instance._T_UnitMgr.List_MDrone.Remove(drone);
                    }
                }
            }
        }

        [HarmonyPrefix]
        [HarmonyPatch(typeof(LoadingSceneMgr), "Start")]
        public static void LoadingSceneMgr_Start()
        {
            //加载时将无人机设置为关闭
            isActiveQueenUAV = false;
        }

        private static void ActiveQueenUAV(bool isActive)
        {
            isActiveQueenUAV = isActive;
            var str_isActiveQueenUAV = isActiveQueenUAV ? "开" : "关";
            GameMgr.Instance._CenterAlarmUI.CenterAlarmCustomSet($"便携式挖矿无人机:{str_isActiveQueenUAV}", new Color(0f, 0.956f, 0f, 1f));
            if (isActiveQueenUAV)
            {
                Building_MiningCompany buiding = (Building_MiningCompany)GameMgr.Instance._BuildingMgr.BuildSet(BuildingName.MiningCompany, GameMgr.Instance._T_UnitMgr.m_Queen.transform.position);
                if(buiding != null)
                {
                    buiding.transform.SetParent(GameMgr.Instance._T_UnitMgr.m_Queen.transform);
                    buiding.m_ID = QueenUAV_ID;
                    buiding.m_Box.enabled = false;
                    buiding.m_Body.gameObject.SetActive(false);
                    buiding.m_Range = 10;
                    buiding.AlarmSet(BuildState.Basic);
                    buiding.Building_Update3();
                    buiding.NGT_Effect_Clear();

                }                
            }
            else
            {
                Building_MiningCompany building = (Building_MiningCompany)GameMgr.Instance._T_UnitMgr.m_Queen.GetComponentInChildren<Building>();
                if(building != null)
                {
                    building.BuildingDemolition(false);
                }
            }
        }
    }
}
